///
/// @file    threadpool.c
/// @author  lemon(haohb13@gmail.com)
/// @date    2022-06-06 11:01:26
///

#include "threadpool.h"
#include "server.h" 
void threadpoolInit(thread_pool_t* pthreadpool, int threadNum)
{
    pthreadpool->threadNumber = threadNum;
    pthreadpool->threads = (pthread_t*)calloc(threadNum, sizeof(pthread_t));
    queueInit(&pthreadpool->queue);
}

void threadpoolDestroy(thread_pool_t* pthreadpool)
{
    free(pthreadpool->threads);
    queueDestroy(&pthreadpool->queue);
}

void threadpoolStart(thread_pool_t * pthreadpool)
{
    for(int idx = 0; idx < pthreadpool->threadNumber; ++idx) {
        int ret = pthread_create(&pthreadpool->threads[idx],
                                 NULL, 
                                 threadFunc, 
                                 pthreadpool);
        THREAD_ERROR_CHECK(ret, "pthread_create");
    }
}

void* threadFunc(void* arg)
{
    //每一个子线程要做的事儿
    printf("sub thread %ld is runing\n", pthread_self());
    thread_pool_t * pthreadpool = (thread_pool_t*)arg;
    while(1) {
        int peerfd = taskDequeue(&pthreadpool->queue);
        if(peerfd > 0) {
            int length;
            int ret=recv(peerfd,&length,4,MSG_WAITALL);

            char Command[10]={0};
            ret=recv(peerfd,Command,length,MSG_WAITALL);

            char fileName[20]={0};

            ret=recv(peerfd,&length,4,MSG_WAITALL);
            ret=recv(peerfd,fileName,length,MSG_WAITALL);

            char responseMsg[50]={0};

            if(strcmp(Command,"cd")==0){
                strcpy( responseMsg,CdDir(fileName));
            }else if(strcmp(Command,"ls")==0){
                strcpy(responseMsg,LsDir(fileName));
            }else if(strcmp(Command,"pwd")==0){
                strcpy(responseMsg,PwdDir());
            }else if(strcmp(Command,"puts")==0){
                strcpy(responseMsg,RecvFile(peerfd));
            }else if(strcmp(Command,"gets")==0){
                strcpy(responseMsg,SendFile(fileName,peerfd));
            }else if(strcmp(Command,"rm")==0){
                strcpy(responseMsg,ReFile(fileName));
            }else if(strcmp(Command,"mkdir")==0){
                strcpy(responseMsg,MkDir(fileName));
            }else{
                strcpy(responseMsg,"ERROR COMMAND!\nPlease type in another command\n");
            }
            write(peerfd,responseMsg,strlen(responseMsg)); 
        } else {
            break;
        }
    }
    printf("sub thread %ld is ready to exit\n", pthread_self());
    pthread_exit(0);
}
